package com.cyt.sys.service.impl;

import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.dao.*;
import com.cyt.sys.model.po.*;
import com.cyt.sys.model.vo.SysVersionVo;
import com.cyt.sys.service.SysVersionService;
import com.cyt.sys.util.DESHelper;
import com.cyt.sys.util.Md5Base64;
import com.cyt.sys.util.PostClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by cykj2018713 on 2019/4/3.
 */
@Service("SysVersionServiceImpl")
public class SysVersionServiceImpl extends BaseServiceImpl<SysVersion> implements SysVersionService {

    private static final Logger LOG = Logger.getLogger(SysVersionServiceImpl.class);


    @Autowired
    private SysVersionDao sysVersionDao;
    @Resource
    private SysAppModuleDao sysAppModuleDao;
    @Resource
    private SysAppModuleEnDao sysAppModuleEnDao;
    @Resource
    private SysLisenceManageDao sysLisenceManageDao;
    @Resource
    private SysVersionEnDao sysVersionEnDao;
    @Resource
    private SysAppMenuDao sysAppMenuDao;
    @Resource
    private SysAppMenuEnDao sysAppMenuEnDao;

    private static String VERSION_SUCCESS_VALUE="版本信息加密成功";

    private static String RECEIVE_VERSION_SUCCESS_VALUE="success";

    private static String RECEIVE_VERSION_FAIL_VALUE="faile";

    private static String SEND_VERSION_SUCCESS_VALUE="版本信息下发成功";

    private static String SEND_VERSION_FAIL_VALUE="版本信息接下发失败";

    private static String SEND_VERSION_URL="/api/baseVersion/receiveDate";



    /**
     * 分页查询
     *
     * @author sunli
     * @date 2019-04-19
     * @param sysVersionVo
     * @param pageSize
     * @param pageNum
     * @return ReturnResult
     */
    @Override
    public ReturnResult page(SysVersionVo sysVersionVo, int pageSize, int pageNum) {
        //查询版本数据的集合
        List<SysVersion> list= sysVersionDao.getVersionList(sysVersionVo);
        PageInfo<SysVersion> page=new PageInfo<SysVersion>(list);
        Map<String,Object> map=new HashedMap();
        map.put("page",page.getList());
        return new ReturnResult(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     *  添加or修改
     *
     *  @author sunli
     *  @date 2019-04-09
     *  @param baseVsersionVo
     *  @return ReturnResult
     */
    @Override
    public ReturnResult saveOrUpdate(SysVersionVo baseVsersionVo) {
        ReturnResult message;
        if(baseVsersionVo.getId()==null || "".equals(baseVsersionVo.getId()) ){

            LOG.debug("执行添加操作");
            SysVersion version=new SysVersion();

            version.setId(BaseUtil.uId());
            version.setVersionNumber(baseVsersionVo.getVersionNumber());
            version.setContent(baseVsersionVo.getContent());
            version.setCreateTime(new Date());
            version.setStatus(baseVsersionVo.getStatus());
            version.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            version.setApplyId(baseVsersionVo.getApplyId());
            version.setReleaseName(baseVsersionVo.getReleaseName());
            SysAppModule app= sysAppModuleDao.selectByPrimaryKey(baseVsersionVo.getApplyId());
            version.setApplyName(app.getName());

            int num= sysVersionDao.insert(version);
            if(num<=0){
                return new ReturnResult(BaseConstant.DATABASE_ERROR_INSERT);
            }
        }else{
            LOG.debug("执行更新操作");

            SysVersion sysVersion = sysVersionDao.selectByPrimaryKey(baseVsersionVo.getId());
            if(StringUtil.isNotEmpty(baseVsersionVo.getApplyId())){
                SysAppModule app= sysAppModuleDao.selectByPrimaryKey(baseVsersionVo.getApplyId());
                sysVersion.setApplyName(app.getName());
            }else{
                sysVersion.setApplyName(baseVsersionVo.getApplyName());
            }
            sysVersion.setVersionNumber(baseVsersionVo.getVersionNumber());
            sysVersion.setContent(baseVsersionVo.getContent());
            sysVersion.setUpdateTime(new Date());
            sysVersion.setStatus(baseVsersionVo.getStatus());
            sysVersion.setRemoveTag(sysVersion.getRemoveTag());
            sysVersion.setApplyId(baseVsersionVo.getApplyId());
            sysVersion.setReleaseName(baseVsersionVo.getReleaseName());
            int count= sysVersionDao.updateByPrimaryKey(sysVersion);
            if(count<=0){
                return new ReturnResult(BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_MSG);
    }


    /**
     * 根据id删除版本信息
     *
     * @author sunli
     * @date 2019-04-10
     * @param ids 版本的ids
     * @return ReturnResult
     */
    public ReturnResult delete(String ids){
        String[] idList=ids.split(",");
        int num=0;
        for (String id:idList){
            SysVersion version = sysVersionDao.selectByPrimaryKey(id);
            version.setRemoveTag(BaseConstant.REMOVE_TAG_YES);
            num= sysVersionDao.updateByPrimaryKey(version);
        }

        if(num>0){
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_DEL);
        }else{
            return new ReturnResult(BaseConstant.DATABASE_ERROR_DEL);
        }
    }

    @Override
    public SysVersion selectVersionById(String id) {
        SysVersion version = sysVersionDao.selectByPrimaryKey(id);
        return version;
    }

    @Override
    public ReturnResult getVersionList(String status) {
        String Vstatus="1";
        List<SysVersion> lists=new ArrayList<SysVersion>();
        List<SysVersion> list= sysVersionDao.getVersiondByStatus(Vstatus);
        lists.addAll(list);
        if (lists != null) {
            return new ReturnResult(lists);
        }else{
            return new ReturnResult(ErrorCode.CODE_201, ErrorCode.CODE_201_MSG);
        }
    }

    /**
     * 对版本信息加密进行下发
     *
     * @author sunli
     * @date 2019-04-17
     * @param url rest接口地址
     * @param id 版本id
     * @return ReturnResult
     */
    @Override
    public ReturnResult sendVersion(String url,String id) {
        SysLisenceManage baseLisenceManage = sysLisenceManageDao.selectByPrimaryKey(id);
        SysVersion sysVersion = sysVersionDao.selectByPrimaryKey(baseLisenceManage.getVersonId());
        String lisence =baseLisenceManage.getLisence();
        SysVersionEn sysVersionEn =new SysVersionEn();
        sysVersionEn.setId(DESHelper.encrypt(sysVersion.getId(),lisence));
        sysVersionEn.setApplyId(DESHelper.encrypt(sysVersion.getApplyId(),lisence));
        sysVersionEn.setApplyName(DESHelper.encrypt(sysVersion.getApplyName(),lisence));
        sysVersionEn.setContent(DESHelper.encrypt(sysVersion.getContent(),lisence));
        sysVersionEn.setReleaseName(DESHelper.encrypt(sysVersion.getReleaseName(),lisence));
        sysVersionEn.setRemoveTag(DESHelper.encrypt(sysVersion.getRemoveTag(),lisence));
        sysVersionEn.setVersionNumber(DESHelper.encrypt(sysVersion.getVersionNumber(),lisence));
        sysVersionEn.setCreator(DESHelper.encrypt(sysVersion.getCreator(),lisence));
        sysVersionEn.setStatus(DESHelper.encrypt(sysVersion.getStatus(),lisence));
        List<SysVersionEn> baseVersionList=new ArrayList<SysVersionEn>();
        baseVersionList.add(sysVersionEn);
        RestTemplate restTemplate = new RestTemplate();
        url = url+SEND_VERSION_URL;
        //String url="http://127.0.0.1:8080/api/baseVersion/receiveDate";//需要外置
        JSONArray jsonObject = JSONArray.fromObject(baseVersionList);
        String message= PostClient.postRequest(restTemplate,jsonObject.toString(),url);
        if(message.equals("success")){
            return new ReturnResult(SEND_VERSION_FAIL_VALUE);
        }else{
            return new ReturnResult(SEND_VERSION_FAIL_VALUE);
        }
    }

    /**
     * 处理下发的数据
     *
     * @author sunli
     * @date 2019-04-18
     * @param baseVersion 版本对象
     * @return
     */
    @Override
    public ReturnResult receiveVersionData(SysVersionEn baseVersion) {
        int num= sysVersionEnDao.insert(baseVersion);
        if(num<=0){
            return new ReturnResult(BaseConstant.CODE_SUCCESS);
        }
        return new ReturnResult(BaseConstant.CODE_ERROR);
    }

    /**
     * 根据lisence加密版本表
     *
     *@author dingxu
     *@date 2019-04-09 14:25
     *@param lisenceId 主键
     *@return ReturnResult
     */
    @Override
    public ReturnResult encordBaseVersion(String lisenceId) {
        SysLisenceManage baseLisenceManage= sysLisenceManageDao.selectByPrimaryKey(lisenceId);
        String lisence=baseLisenceManage.getLisence();
        //查询所有版本号
        //清空加密表
        sysVersionEnDao.truncateVersionEn();
        //加密版本表
        List<SysVersion> list= sysVersionDao.selectAll();
        for(SysVersion sysVersion :list){
            SysVersionEn sysVersionEn =new SysVersionEn();
            sysVersionEn.setId(DESHelper.encrypt(sysVersion.getId(),lisence));
            sysVersionEn.setApplyId(DESHelper.encrypt(sysVersion.getApplyId(),lisence));
            sysVersionEn.setApplyName(DESHelper.encrypt(sysVersion.getApplyName(),lisence));
            sysVersionEn.setContent(DESHelper.encrypt(sysVersion.getContent(),lisence));
            sysVersionEn.setReleaseName(DESHelper.encrypt(sysVersion.getReleaseName(),lisence));
            sysVersionEn.setRemoveTag(DESHelper.encrypt(sysVersion.getRemoveTag(),lisence));
            sysVersionEn.setVersionNumber(DESHelper.encrypt(sysVersion.getVersionNumber(),lisence));
            sysVersionEn.setCreator(DESHelper.encrypt(sysVersion.getCreator(),lisence));
            sysVersionEn.setStatus(DESHelper.encrypt(sysVersion.getStatus(),lisence));
            sysVersionEnDao.insert(sysVersionEn);
        }
        //清空应用加密表
        sysAppModuleEnDao.truncateAppModuleEn();
        //加密应用表
        List<SysAppModule> sysAppModuleList = sysAppModuleDao.selectAll();
        for(SysAppModule sysAppModule : sysAppModuleList){
            SysAppModuleEn sysAppModuleEn =new SysAppModuleEn();
            sysAppModuleEn.setCode(DESHelper.encrypt(sysAppModule.getCode(),lisence));
            sysAppModuleEn.setDescription(DESHelper.encrypt(sysAppModule.getDescription(),lisence));
            sysAppModuleEn.setId(DESHelper.encrypt(sysAppModule.getId(),lisence));
            sysAppModuleEn.setMenuIds(DESHelper.encrypt(sysAppModule.getMenuIds(),lisence));
            sysAppModuleEn.setName(DESHelper.encrypt(sysAppModule.getName(),lisence));
            sysAppModuleEn.setPrivateKey(DESHelper.encrypt(sysAppModule.getPrivateKey(),lisence));
            sysAppModuleEn.setPublicKey(DESHelper.encrypt(sysAppModule.getPublicKey(),lisence));
            sysAppModuleEn.setRemoveTag(DESHelper.encrypt(sysAppModule.getRemoveTag(),lisence));
            sysAppModuleEn.setStatus(DESHelper.encrypt(sysAppModule.getStatus(),lisence));
            sysAppModuleEnDao.insert(sysAppModuleEn);
        }
        //清空应用菜单关联表
        List<SysAppMenu> sysAppMenuList = sysAppMenuDao.selectAll();
        sysAppMenuEnDao.truncateAppMenuEn();
        //加密应用菜单关联表
        for(SysAppMenu sysAppMenu : sysAppMenuList){
            SysAppMenuEn sysAppMenuEn =new SysAppMenuEn();
            sysAppMenuEn.setId(DESHelper.encrypt(sysAppMenu.getId(),lisence));
            sysAppMenuEn.setAppId(DESHelper.encrypt(sysAppMenu.getAppId(),lisence));
            sysAppMenuEn.setMenuId(DESHelper.encrypt(sysAppMenu.getMenuId(),lisence));
            sysAppMenuEnDao.insert(sysAppMenuEn);
        }

        return new ReturnResult(VERSION_SUCCESS_VALUE);
    }

    /**
     * 根据lisence解密版本表
     *
     *@author dingxu
     *@date 2019-04-09 14:25
     *@param lisence 主键
     *@return ReturnResult
     */
    @Override
    public ReturnResult decordBaseVersion(String lisence) throws Exception {
        //查询所有版本号
        //清空菜单表
        sysVersionDao.truncateVersion();
        //解密版本表
        List<SysVersionEn> list= sysVersionEnDao.selectAll();
        List<SysVersion> listV=new ArrayList<SysVersion>();
        for(SysVersionEn sysVersionEn :list){
            SysVersion sysVersion =new SysVersion();
            sysVersion.setId(DESHelper.decryptor(sysVersionEn.getId(),lisence));
            sysVersion.setApplyId(DESHelper.decryptor(sysVersionEn.getApplyId(),lisence));
            sysVersion.setApplyName(DESHelper.decryptor(sysVersionEn.getApplyName(),lisence));
            sysVersion.setContent(DESHelper.decryptor(sysVersionEn.getContent(),lisence));
            sysVersion.setReleaseName(DESHelper.decryptor(sysVersionEn.getReleaseName(),lisence));
            sysVersion.setRemoveTag(DESHelper.decryptor(sysVersionEn.getRemoveTag(),lisence));
            sysVersion.setVersionNumber(DESHelper.decryptor(sysVersionEn.getVersionNumber(),lisence));
            sysVersion.setCreator(DESHelper.decryptor(sysVersionEn.getCreator(),lisence));
            sysVersion.setStatus(DESHelper.decryptor(sysVersionEn.getStatus(),lisence));
            // baseVersionDao.insert(sysVersion);
            listV.add(sysVersion);
        }
        SysVersion nowSysVersion =new SysVersion();
        String lisenceVersionId= Md5Base64.decryptBASE64(lisence);
        for(SysVersion sysVersion :listV){
            if(sysVersion.getId().equals(lisenceVersionId)){
                sysVersionDao.insert(sysVersion);
                nowSysVersion = sysVersion;
            }
        }
        //清空应用表
        sysAppModuleDao.truncateAppModule();
        List<SysAppModuleEn> sysAppModuleEnList = sysAppModuleEnDao.selectAll();
        List<SysAppModule> sysAppModuleList = new ArrayList<SysAppModule>();
        //解密应用表
        for(SysAppModuleEn sysAppModuleEn : sysAppModuleEnList){
            SysAppModule sysAppModule =new SysAppModule();
            sysAppModule.setCode(DESHelper.decryptor(sysAppModuleEn.getCode(),lisence));
            sysAppModule.setDescription(DESHelper.decryptor(sysAppModuleEn.getDescription(),lisence));
            sysAppModule.setId(DESHelper.decryptor(sysAppModuleEn.getId(),lisence));
            sysAppModule.setMenuIds(DESHelper.decryptor(sysAppModuleEn.getMenuIds(),lisence));
            sysAppModule.setName(DESHelper.decryptor(sysAppModuleEn.getName(),lisence));
            sysAppModule.setPrivateKey(DESHelper.decryptor(sysAppModuleEn.getPrivateKey(),lisence));
            sysAppModule.setPublicKey(DESHelper.decryptor(sysAppModuleEn.getPublicKey(),lisence));
            sysAppModule.setRemoveTag(DESHelper.decryptor(sysAppModuleEn.getRemoveTag(),lisence));
            sysAppModule.setStatus(DESHelper.decryptor(sysAppModuleEn.getStatus(),lisence));
            sysAppModule.setCreateTime(new Date());
            sysAppModuleList.add(sysAppModule);
            // baseAppModuleDao.insert(sysAppModule);
        }
        for(SysAppModule sysAppModule : sysAppModuleList){
            if(sysAppModule.getId().equals(nowSysVersion.getApplyId())){
                sysAppModuleDao.insert(sysAppModule);
            }
        }
        //清空应用—菜单表
        sysAppMenuDao.truncateAppMenu();
        //解密应用—菜单表
        List<SysAppMenuEn> sysAppMenuEnList = sysAppMenuEnDao.selectAll();
        List<SysAppMenu> sysAppMenuList =new ArrayList<SysAppMenu>();
        for(SysAppMenuEn sysAppMenuEn : sysAppMenuEnList){
            SysAppMenu sysAppMenu =new SysAppMenu();
            sysAppMenu.setId(DESHelper.decryptor(sysAppMenuEn.getId(),lisence));
            sysAppMenu.setAppId(DESHelper.decryptor(sysAppMenuEn.getAppId(),lisence));
            sysAppMenu.setMenuId(DESHelper.decryptor(sysAppMenuEn.getMenuId(),lisence));
            sysAppMenu.setCreateTime(new Date());
            if(sysAppMenu.getAppId().equals(nowSysVersion.getApplyId())){
                sysAppMenuList.add(sysAppMenu);
            }
            // baseAppMenuDao.insert(sysAppMenu);
        }
        for(SysAppMenu sysAppMenu : sysAppMenuList){
            sysAppMenuDao.insert(sysAppMenu);
        }
        //
        return new ReturnResult(VERSION_SUCCESS_VALUE);
    }
}
